package com.mbbmap.security.action;

import java.sql.SQLException;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mbbmap.app.dao.SysLogDao;
import com.mbbmap.app.dao.UserDao;
import com.mbbmap.app.exception.LogonException;
import com.mbbmap.app.home.SecUsersHome;
import com.mbbmap.app.home.SysLogHome;
import com.mbbmap.security.dao.SecUserDao;
import com.mbbmap.security.manager.UserManager;
import com.mbbmap.util.Constants;

public class UserAction extends CommonDispatchAction {
	public ActionForward resetUser(ActionMapping mapping,
		    ActionForm form, HttpServletRequest request,
		    HttpServletResponse response) throws Exception {
		
		final String PROG_ID="UserAction.UserAction";
	    HttpSession session = request.getSession(false);
		String strEMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
		String strMerchant = "";
		String currLogonUserId= (String) session.getAttribute(Constants.LOGINID);

		
		String roleCode =(String) session.getAttribute(Constants.LOGON_USER_ROLE);
		if (roleCode == null || roleCode.trim().equals("")) {
		    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
		}
		if ((strEMerchant != null) && (!strEMerchant.equals(""))){
			//strMerchant= EncryptionHelper.decrypt(strEMerchant,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
		    strMerchant= strEMerchant;
		}else{
			strMerchant = "";
			return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
		}
		if(!isTokenValid(request)){
			System.out.println("Token validation failed!");
			session.invalidate();
			return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
		}else{
			resetToken(request);
			System.out.println("Token validation passed!");
		}
		System.out.println("Reset user action.");
		String userId = sanitizePwd(request.getParameter("userid"));
		String pass1 = sanitizePwd(request.getParameter("pass1"));
		String pass2 = sanitizePwd(request.getParameter("pass2"));
		
		SysLogDao sysLogDao = new SysLogDao();
		request.setAttribute("userid", userId);
		request.setAttribute("pass1", pass1);
		request.setAttribute("pass2", pass2);
		
		// check if user exists
		if (!UserManager.userExists(userId)){
			request.setAttribute("msg", "User "+ userId +" does not exists. Please Try Again.");
			request.setAttribute("msg_id", "MSG001");
			return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
		}
		// reset password
		if (UserManager.resetPassword(userId,pass1)>0){
			request.setAttribute("msg", "Password for User "+ userId +" was successfully reset.");
			request.setAttribute("msg_id", "MSG999");
			
			
			sysLogDao.setActivityCode(Constants.ACT_CODE_SECURITY);
			sysLogDao.setAcctID(strMerchant);
			sysLogDao.setActivityName(PROG_ID);
			sysLogDao.setUserID(currLogonUserId);
			sysLogDao.setRole(roleCode);
			sysLogDao.setUserField1("Password Reset on User =" + userId);
			
			sysLogDao.setStatus(Constants.ACT_STATUS_SUCCESS);
			
			SysLogHome.getInstance().insertSysLog(sysLogDao);
		}else{
			request.setAttribute("msg", "Failed to Reset Password. Please Try Again.");
			request.setAttribute("msg_id", "MSG002");
		}
		return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
	}
	public ActionForward changeInitial(ActionMapping mapping,
		    ActionForm form, HttpServletRequest request,
		    HttpServletResponse response) throws SQLException {
		System.out.println("Change initial action.");
		String remoteIPaddr = request.getRemoteAddr();
		String remoteHostName = request.getRemoteHost();
		HttpSession session = request.getSession(false);
		SecUserDao oUserDao = (SecUserDao) session.getAttribute(Constants.LOGGED_USER);
		String userId = oUserDao.getLogonId();
		Properties paramProp = (Properties) session.getAttribute(Constants.PROPERTIES_PARAMETER);
		
		final String PROG_ID="UserAction.UserAction";
		String strMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
		String currLogonUserId= (String) session.getAttribute(Constants.LOGINID);
		String roleCode =(String) session.getAttribute(Constants.LOGON_USER_ROLE);
		SysLogDao sysLogDao = new SysLogDao();
		
		String oldpass = sanitizePwd(request.getParameter("oldpass"));
		String pass1 = sanitizePwd(request.getParameter("pass1"));
		String pass2 = sanitizePwd(request.getParameter("pass2"));
		
		request.setAttribute("oldpass", userId);
		request.setAttribute("pass1", pass1);
		request.setAttribute("pass2", pass2);
		
		
		// check if user exists
		System.out.println("Check user exist.");
		if (!UserManager.isValidPassword(userId, oldpass)){
			request.setAttribute("msg", "Current password is wrong. Please Try Again.");
			request.setAttribute("msg_id", "MSG001");
		}else{
			// change password
			sysLogDao.setActivityCode(Constants.ACT_CODE_SECURITY);
			sysLogDao.setAcctID(strMerchant);
			sysLogDao.setActivityName(PROG_ID);
			sysLogDao.setUserID(currLogonUserId);
			sysLogDao.setRole(roleCode);
			sysLogDao.setUserField1("Password changed on User =" + userId);
			
			sysLogDao.setStatus(Constants.ACT_STATUS_SUCCESS);
			SysLogHome.getInstance().insertSysLog(sysLogDao);
			System.out.println("Change password.");
			try {
				session.setAttribute(Constants.LOGGED_USER,SecUsersHome.getInstance().loginChangePwd(strMerchant, userId, oldpass, pass1, remoteIPaddr + " / " + remoteHostName, paramProp));
			} catch (LogonException le) {
				short code = le.getErrorCode(); 
				if (code == LogonException.NEW_PWD_EXIST){
					//SecUserDao userDao = SecUsersHome.getInstance().login(strMerchant, strUserID, strUserPWD, remoteIPaddr + " / " + remoteHostName);
					//session.setAttribute(Constants.LOGGED_USER,userDao);
					//session.setAttribute(Constants.SEC_USER_OBJ,userDao);
					//session.setAttribute(Constants.LOGON_ACCESS_LIST, secGroupAccessList);
					request.setAttribute("msg", "PASSWORD EXIST IN HISTORY, PLEASE USE ANOTHER PASSWORD.");
					//strErrLogonMsg = "PASSWORD EXIST IN HISTORY, PLEASE USE ANOTHER PASSWORD.";
					String nextPage = Constants.KEY_ACTION_CHANGE_PWD;
					return mapping.findForward(nextPage);
				}
				if (code == LogonException.USER_ID_PWD_SAME){
					request.setAttribute("msg", "PASSWORD CANNOT BE SAME AS USER ID.");
					String nextPage = Constants.KEY_ACTION_CHANGE_PWD;
					return mapping.findForward(nextPage);
				}
				le.printStackTrace();
			}
			System.out.println("Password change is successful.");
			request.setAttribute("msg", "Password change successful, Please login new password.");
			request.setAttribute("msg_id", "MSG999");
			
		}
		return mapping.findForward("changepwd");
		
	}
	public ActionForward changePwd(ActionMapping mapping,
		    ActionForm form, HttpServletRequest request,
		    HttpServletResponse response) throws Exception {
	    HttpSession session = request.getSession(false);
	    SecUserDao oSecUserDao = (SecUserDao) session.getAttribute(Constants.LOGGED_USER);// read user session time
		
		String strFwd = "";
		if (oSecUserDao == null){
			strFwd ="sessionError";
		}
		if(!isTokenValid(request)){
			System.out.println("Token validation failed!");
			session.invalidate();
			return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
		}else{
			resetToken(request);
			System.out.println("Token validation passed!");
		}
		if (oSecUserDao == null){// if the session expire, it will bring user to timeout screen
			return mapping.findForward(strFwd);
		}
		else{
		return mapping.findForward("changepwd");
		}
		
	}
}
